package com.guigu.qingcheng.systemservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guigu.qingcheng.pojo.system.TbAdmin;
import com.guigu.qingcheng.pojo.system.TbAdminRole;
import com.guigu.qingcheng.pojo.system.TbAdminRoleList;
import com.guigu.qingcheng.pojo.system.TbRole;
import com.guigu.qingcheng.systemservice.config.BCrypt;
import com.guigu.qingcheng.systemservice.mapper.TbAdminMapper;
import com.guigu.qingcheng.systemservice.service.TbAdminRoleService;
import com.guigu.qingcheng.systemservice.service.TbAdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guigu.qingcheng.systemservice.service.TbRoleService;
import com.guigu.qingcheng.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-07-08
 */
@Service
public class TbAdminServiceImpl extends ServiceImpl<TbAdminMapper, TbAdmin> implements TbAdminService {

    @Autowired
    private TbAdminService tbAdminService;

    @Autowired
    private TbAdminRoleService tbAdminRoleService;

    @Autowired
    private TbRoleService tbRoleService;

    @Override
    public R updateByUser(Map<String, Object> zhhuForm) {
        // 判断有误该user
        QueryWrapper<TbAdmin> wapper = queryWrapper(zhhuForm);
        List<TbAdmin> list = tbAdminService.list(wapper);
        if (list.size() == 0) {
            return R.error().data("message", "该用户不存在");
        } else {
            // 判断旧密码是否正确
            for (TbAdmin a : list) {
                Boolean f = BCrypt.checkpw(zhhuForm.get("oldPassword").toString(), a.getPassword());
                if (f == false) {
                    return R.error().data("message", "旧密码错误");
                } else {
                    // 判断新密码与确认新密码是否正确
                    if (!zhhuForm.get("newPassword").toString().equals(zhhuForm.get("resPassword").toString())) {
                        return R.error().data("message", "两次密码不一致");
                    } else {
                        // 修改账户
                        TbAdmin ad = new TbAdmin();
                        String psalt = BCrypt.gensalt(); //盐 29个字符，随机生成
                        String newPassword = zhhuForm.get("newPassword").toString();
                        String password = BCrypt.hashpw(newPassword, psalt);
                        ad.setId(Integer.parseInt(zhhuForm.get("id").toString()));
                        ad.setLoginName(zhhuForm.get("loginName").toString());
                        ad.setPassword(password);
                        ad.setStatus("1");
                        Boolean res = tbAdminService.updateById(ad);
                        if (!res) {
                            return R.error().data("message", "修改失败");
                        }
                    }
                }
            }
        }
        return R.ok().data("message", "修改成功");
    }

    @Transactional
    @Override
    public Boolean addSave(Map<String, Object> adminRoleForm) {
        TbAdmin ad = new TbAdmin();
        ad.setLoginName(adminRoleForm.get("loginName").toString());
        ad.setStatus("1");
        String psalt = BCrypt.gensalt(); //盐 29个字符，随机生成
        String newPassword = adminRoleForm.get("password").toString();
        String password = BCrypt.hashpw(newPassword, psalt);
        ad.setPassword(password);
        Boolean f = tbAdminService.save(ad);
        int aid = ad.getId();
        List list = (List) adminRoleForm.get("rid");
        int res = 0;
        for(int a = 0; a < list.size(); a ++) {
            TbAdminRole ar = new TbAdminRole();
            ar.setAdminId(aid);
            ar.setRoleId((Integer) list.get(a));
            Boolean b = tbAdminRoleService.save(ar);
            if(b){
                res++ ;
            }
        }
        if(f == true && res == list.size())
            return true;
        return false;
    }

    @Transactional
    @Override
    public Boolean updateAdmin(Map<String, Object> adminRoleForm) {
        //修改账户信息
        TbAdmin admin = new TbAdmin();
        admin.setId(Integer.parseInt(adminRoleForm.get("id").toString()));
        admin.setStatus("1");
        admin.setLoginName(adminRoleForm.get("loginName").toString());
        //密码加密（密码不为空的情况下）
        if(adminRoleForm.get("password").toString() != null && !"".equals(adminRoleForm.get("password").toString())){
            String psalt = BCrypt.gensalt(); //盐 29个字符，随机生成
            String newPassword = adminRoleForm.get("password").toString();
            String password = BCrypt.hashpw(newPassword, psalt);
            admin.setPassword(password);
        }else {
            TbAdmin a = tbAdminService.getById(Integer.parseInt(adminRoleForm.get("id").toString()));
            admin.setPassword(a.getPassword());
        }
        Boolean f = tbAdminService.updateById(admin);

        //删除账户角色中间表对应数据
        Boolean f2 = tbAdminRoleService.removeById(Integer.parseInt(adminRoleForm.get("id").toString()));
        //添加账户角色中间表对应数据
        List list = (List) adminRoleForm.get("rid");
        int sum = 0;
        for(int a = 0; a < list.size(); a++){
            TbAdminRole tbAdminRole = new TbAdminRole();
            tbAdminRole.setAdminId(admin.getId());
            tbAdminRole.setRoleId((Integer) list.get(a));
            Boolean f3 = tbAdminRoleService.save(tbAdminRole);
            if(f3){
                sum++ ;
            }
        }
        if(f == true && f2 == true&& sum == list.size())
            return true;
        return false;
    }

    @Override
    public Boolean updateStatus(Integer id, String status) {
        // 查询该成员
        TbAdmin ad = tbAdminService.getById(id);
        ad.setStatus(status);
        //修改状态
        Boolean f = tbAdminService.updateById(ad);
        return f;
    }

    /**
     * 条件查询
     * @param searchMap， 查询所带条件
     * @return
     */
    @Override
    public List<TbAdmin> findList(Map<String, Object> searchMap) {
        QueryWrapper<TbAdmin> wapper = queryWrapper(searchMap);
        List<TbAdmin> list = tbAdminService.list(wapper);
        return list;
    }

    /**
     * 分页条件查询
     * @param page 页号
     * @param size 页大小
     * @param searchMap 查询所带条件
     * @return
     */
    @Override
    public Page<TbAdmin> findPage(Integer page, Integer size, Map<String, Object> searchMap) {
        Page<TbAdmin> pg = new Page<TbAdmin>(page, size);
        QueryWrapper<TbAdmin> wapper = queryWrapper(searchMap);
        IPage<TbAdmin> list = tbAdminService.page(pg, wapper);
        return pg;
    }

    @Override
    public List<TbAdminRoleList> findPage2(Integer page, Integer size, Map<String, Object> searchMap) {
        // 先查询所有用户
        QueryWrapper<TbAdmin> adminWrapper = new QueryWrapper<>();
        if(searchMap != null){
            if(searchMap.get("loginName") != null && !"".equals(searchMap.get("loginName"))){
                adminWrapper.like("login_name", searchMap.get("loginName"));
            }if(searchMap.get("id") != null && !"".equals(searchMap.get("id"))){
                adminWrapper.eq("id", searchMap.get("id"));
            }
        }
        Page<TbAdmin> pg = new Page<TbAdmin>(page, size);
//        List<TbAdmin> adminList = tbAdminService.list(adminWrapper);
        IPage<TbAdmin> adminList = tbAdminService.page(pg, adminWrapper);
        // 再根据所有的用户id查询出角色id
        // 再根据角色id查询到角色名称
        List<TbAdminRoleList> list = new ArrayList<>();
        for(TbAdmin a: adminList.getRecords()){
            TbAdminRoleList tarlList = new TbAdminRoleList();
            QueryWrapper<TbAdminRole> wa = new QueryWrapper<>();
            wa.eq("admin_id", a.getId());
            List<TbAdminRole> tar = tbAdminRoleService.list(wa);
            List roleList = new ArrayList();
            List roleList2 = new ArrayList();
            for(TbAdminRole r: tar){
                TbRole tr = tbRoleService.getById(r.getRoleId());
                roleList.add(r.getRoleId());
                roleList2.add(tr.getName());
            }
            tarlList.setRId(roleList);
            tarlList.setRName(roleList2);
            tarlList.setAId(a.getId());
            tarlList.setAName(a.getLoginName());
            tarlList.setStatus(a.getStatus());
            list.add(tarlList);
        }
        return list;
    }

    /**
     * 高级组合查询封装对象
     * @param searchMap
     * @return
     */
    public QueryWrapper<TbAdmin> queryWrapper(Map<String, Object> searchMap){
        QueryWrapper<TbAdmin> wapper = new QueryWrapper<TbAdmin>();
        if(searchMap != null){
            if(searchMap.get("id") != null && !"".equals(searchMap.get("id")))
                wapper.eq("id", searchMap.get("id"));
            if(searchMap.get("loginName") != null && !"".equals(searchMap.get("loginName")))
                wapper.eq("login_name", searchMap.get("loginName"));
        }
        return wapper;
    }
}
